from dataclasses import dataclass
from datetime import datetime
from typing import Optional

@dataclass
class WeiboPost:
    """微博帖子数据模型"""
    id: str
    content: str
    user_id: str
    user_name: str
    publish_time: datetime
    reposts_count: int = 0
    comments_count: int = 0
    likes_count: int = 0
    url: Optional[str] = None
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'content': self.content,
            'user_id': self.user_id,
            'user_name': self.user_name,
            'publish_time': self.publish_time.isoformat(),
            'reposts_count': self.reposts_count,
            'comments_count': self.comments_count,
            'likes_count': self.likes_count,
            'url': self.url
        }
    
    @classmethod
    def from_dict(cls, data: dict):
        """从字典创建对象"""
        return cls(
            id=data['id'],
            content=data['content'],
            user_id=data['user_id'],
            user_name=data['user_name'],
            publish_time=datetime.fromisoformat(data['publish_time']),
            reposts_count=data.get('reposts_count', 0),
            comments_count=data.get('comments_count', 0),
            likes_count=data.get('likes_count', 0),
            url=data.get('url')
        )